package com.bys.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bys.constant.HttpContant;
import com.bys.exception.BysOaSystemException;
import com.bys.system.mapper.SysUserRoleMapper;
import com.bys.system.model.SysRoleModel;
import com.bys.system.model.SysUserModel;
import com.bys.system.mapper.SysUserMapper;
import com.bys.system.model.SysUserRoleModel;
import com.bys.system.service.ISysMenuService;
import com.bys.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bys.system.vo.CreateUserVo;
import com.bys.system.vo.RouterVo;
import com.bys.system.vo.SysUserVo;
import com.bys.system.vo.UserInfoVo;
import com.bys.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * PackageName:  com.bys.system.service.impl
 * ClassName:    SysUserServiceImpl
 * Description:  用户表 服务实现类
 * Author:       bys
 * Date:         2023-03-31
 **/
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserModel> implements ISysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ISysMenuService sysMenuService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteLogic(Long id) {
        SysUserModel sysUserModel = sysUserMapper.selectById(id);
        Optional.ofNullable(sysUserModel).orElseThrow(() -> new BysOaSystemException("不存在该用户"));
        sysUserModel.setIsDeleted(Boolean.TRUE);
        sysUserModel.setUpdateTime(LocalDateTime.now());
        sysUserMapper.updateById(sysUserModel);
    }

    @Override
    public Page<SysUserVo> getUserPage(Integer pageNo, Integer pageSize, SysUserVo sysUserVo) {
        Page<SysUserVo> page = new Page<>(pageNo, pageSize);
        StringBuilder builder = new StringBuilder();
        Page<SysUserVo> sysUserVoPage = sysUserMapper.selectUserPage(page, sysUserVo);
        sysUserVoPage.getRecords().forEach(user -> {
            String ofRole = sysUserRoleMapper.selectRole(user.getId()).stream()
                    .map(SysRoleModel::getRoleName).collect(Collectors.joining(","));
            user.setOfRole(ofRole);
        });
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveUser(CreateUserVo createUserVo) {
        SysUserModel sysUserModel = new SysUserModel();
        BeanUtils.copyProperties(createUserVo, sysUserModel);
        int length = createUserVo.getDeptId().size();
        String deptId = createUserVo.getDeptId().get(length - 1);
        log.info("部门的 id {}", deptId);
        sysUserModel.setDeptId(Long.parseLong(deptId));
        log.info("复制完成的 对象 {}", sysUserModel);
        //    保存用户
        sysUserMapper.insert(sysUserModel);
        //     保存用户的所属角色
        List<Long> roleIds = createUserVo.getOfRole().stream().map(Long::parseLong).collect(Collectors.toList());
        roleIds.forEach(id -> {
            SysUserRoleModel sysUserRoleModel = new SysUserRoleModel();
            sysUserRoleModel.setUserId(sysUserModel.getId());
            sysUserRoleModel.setRoleId(id);
            sysUserRoleMapper.insert(sysUserRoleModel);
        });
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {

        UserInfoVo userInfoVo = new UserInfoVo();
        SysUserModel sysUserModel = sysUserMapper.selectById(userId);
        //     根据 id 获取菜单
        List<RouterVo> menuRouters = sysMenuService.findUserMenu(userId);
        //     根据 id 获取菜单权限
        List<String> permissions = sysMenuService.findUserPermission(userId);
        userInfoVo.setUserId(sysUserModel.getId());
        userInfoVo.setName(sysUserModel.getName());
        userInfoVo.setAvatar(sysUserModel.getHeadUrl());
        userInfoVo.setRoles(new HashSet<>());
        userInfoVo.setRouters(menuRouters);
        userInfoVo.setPermission(permissions);
        return userInfoVo;
    }

    @Override
    public SysUserModel getByUsername(String assignee) {

        return  null;
    }
}
